<?php
namespace app\api\service;

use app\api\logic\Order;
use think\Db;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay', EXTEND_PATH, '.Api.php');
Loader::import('WxPay.WxPay', EXTEND_PATH, '.JsApiPay.php');
Loader::import('WxPay.WxPay', EXTEND_PATH, '.Log.php');

class WxNotify extends \WxPayNotify
{
    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);

        if (array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS"
        ) {
            return true;
        }
        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {
        //初始化日志
        $logHandler = new \CLogFileHandler(dirname(__FILE__) . DIRECTORY_SEPARATOR . "./../../../extend/WxPay/logs/" . date('Y-m-d', time()) . ".log");
        \Log::Init($logHandler, 15);
        \Log::DEBUG("call back:" . json_encode($data));

        if (!array_key_exists("transaction_id", $data)) {
            $msg = "输入参数不正确";
            return false;
        }
        //查询订单，判断订单真实性
        if (!$this->Queryorder($data["transaction_id"])) {
            $msg = "订单查询失败";
            return false;
        }
        if ($data['result_code'] == 'SUCCESS') {
            $model_pay_log = db('pay_log');
            $pay_log = $model_pay_log->where(array('pay_sn' => $data['out_trade_no']))->find();
            if (empty($pay_log)) {
                Log::write("找不到支付单号：" . $data['out_trade_no'] . "的订单");
                return false;
            }
            if ($pay_log['status'] == PAY_SUCCESS) {
                Log::write("该订单已支付，支付单号：" . $data['out_trade_no'] . "的订单",'info');
                return false;
            }
            if($pay_log['money'] != $data['total_fee']){
                Log::write("该订单的金额与实际支付不符，支付单号：" . $data['out_trade_no'] . "的订单",'info');
                return false;
            }
            $result = (new Order())->afterPay($pay_log,1);
            if(array_key_exists('message',$result)) return false;

        } else {
            // 如果出现异常，向微信返回false，请求重新发送通知
            return false;
        }
        return true;
    }


}

